<template>
  <div class="create-page">
    <!-- 顶栏 -->
    <TopBar
      :pageTitle="currentTitle"
      @top-click="handleTopClick"
      :activeP="activeP"
    />

    <!-- 主内容区域(左 - 中 - 右) -->
    <div class="main-body">
      <!-- 左侧菜单 -->
      <aside class="left-panel">
        <LeftMenu
          @openWrite="isWrite = true"
          :has_new="has_new"
          :creation_id="creation_id"
          :activeP="activeP"
          @changeType="changeType"
          @node-click="handleTreeNodeClick"
          @node-command="handleTreeNodeCommand"
          @node-click-bj="handleTreeNodeClickBj"
          @node-command-bj="handleTreeNodeCommandBj"
          @share="handleOpenShare"
          @share2="handleOpenShare2"
        />
      </aside>

      <!-- 中间编辑区域 -->
      <section class="center-panel">
        <!-- 操作按钮栏: AI生成稿题, AI写作导航, 保存, 发布 -->
        <!-- 富文本编辑器 (标题在编辑器内) -->
        <RichEditor
          ref="rich"
          v-if="activeP == 'zj'"
          :currentType="currentType"
          :dataObj="currentDataObj"
          :editId="editId"
          @update-content="onEditorContentChange"
        />
        <BackDetail
          ref="bjDetail"
          v-else
          :dataObj="currentDataBj"
          :editId="editId"
          @update-content="onEditorContentChange"
          @changeDldh="changeDldh"
        />
      </section>

      <!-- 右侧工具栏 -->
      <div class="right-panel" :class="{ openLeft: isWrite }">
        <RightTools
          ref="gj"
          @changeDldh="changeDldh"
          @openWrite="isWrite = true"
        />
      </div>
    </div>
    <Conversation ref="dldh" />
    <el-dialog
      title="AI创作导引"
      :visible.sync="showAiDy"
      width="450px"
      top="40vh"
    >
      <div class="tip">AI写作第一步，建议从这里开始！</div>
      <div class="selectType" @click="isNext = !isNext">
        <i :class="isNext ? 'active el-icon-success' : ''"></i>下次不再提醒
      </div>
      <div class="dialog-footer">
        <el-button @click="goAiDyQx">取消</el-button>
        <el-button type="primary" @click="goAiDy">确定</el-button>
      </div>
    </el-dialog>
    <AIWriteDialog
      @getTaskId="getTaskId"
      @close="isWrite = false"
      v-if="isWrite"
    ></AIWriteDialog>
    <ShareDialog
      :visible.sync="isShare"
      @close="isShare = false"
      :url="shareUrl"
    ></ShareDialog>
  </div>
</template>

<script>
import TopBar from "./components/TopBar.vue";
import RightTools from "./components/RightTools.vue";
import AIWriteDialog from "./components/AIWriteDialog.vue";
import LeftMenu from "./components/LeftMent.vue";
import RichEditor from "./components/RichEditor.vue";
import BackDetail from "./components/BackDetail.vue";
import Conversation from "../../components/Conversation/index.vue";
import {
  creationNoShow,
  getCreationDetail,
  getCreationsList,
} from "@/api/work";

// 如果需要用到后端接口：
import {
  createVolume,
  getVolumeDetail,
  getVolumeList,
  updateVolumeDescription,
  volumeUpdate,
} from "@/api/volumes";
import {
  chapterUpdate,
  editChapterContent,
  getChapterContent,
} from "@/api/chapter";
import { getVersionsContent, versionUpdate } from "@/api/versions";
import { getArchList, getArchMaster } from "@/api/arch";
import { createShareLink, createShareVersionLink } from "@/api/share";
// import { getChapterList, ... } from "@/api/chapters";
import ShareDialog from "./components/ShareDialog.vue";
export default {
  name: "CreatePage",
  components: {
    ShareDialog,
    AIWriteDialog,
    TopBar,
    BackDetail,
    RightTools,
    LeftMenu,
    RichEditor,
    Conversation,
  },
  data() {
    return {
      has_new: false,
      shareUrl: "",
      isShare: false,
      taskId: "",
      isWrite: false,
      showAiDy: false,
      isNext: false,
      activeP: "zj",
      editData: {},
      creation_id: "",
      // 从后端获取或本地模拟
      treeData: [],
      editId: "",
      currentType: "1",
      // 当前选中的节点信息(示例)
      currentTitle: "牧羊少年奇幻之旅", // 顶栏标题
      currentDataObj: {
        title: "",
        content: "",
        description: "",
      },
      currentTypeBj: "1",
      currentDataBj: {},
    };
  },
  mounted() {
    console.log(this.$route.params.id);
    this.creation_id = Number(this.$route.params.id);
    this.getDetail();
    // 如果需要联调后端，可在此调用 getVolumeList(...) / getChapterList(...) 等
  },
  methods: {
    //打开分享章节链接
    handleOpenShare(data) {
      createShareLink({ chapter_id: data.id }).then((res) => {
        this.shareUrl = res;
        this.isShare = true;
      });
    },
    //打开分享版本链接
    handleOpenShare2(data) {
      createShareVersionLink({
        chapter_id: data.chap_id,
        version_id: data.id,
      }).then((res) => {
        this.shareUrl = res;
        this.isShare = true;
      });
    },
    //传给兄弟组件
    getTaskId(id) {
      console.log("收到id了111");
      // this.taskId = id;
      this.$refs.gj.handleCreateStatus(id);
    },
    goAiDyQx() {
      this.showAiDy = false;
      if (this.isNext) {
        this.noShow();
      }
    },
    goAiDy() {
      this.isWrite = true;
      this.showAiDy = false;
    },
    noShow() {
      creationNoShow({ creation_id: Number(this.creation_id) }).then((res) => {
        console.log(res);
      });
    },
    getDetail() {
      getCreationDetail({ creation_id: Number(this.creation_id) }).then(
        (res) => {
          console.log(res);
          this.currentTitle = res.title;
          this.has_new = res.has_new;
          if (res.show_guide) {
            this.showAiDy = true;
          }
          // this.currentDataObj=res.volume
          // this.currentType='1'
        }
      );
    },
    saveJuanDetail() {
      console.log(this.$refs.rich.editorContent);
      volumeUpdate(
        this.editId,
        this.$refs.rich.title,
        this.$refs.rich.editorContent
      ).then((res) => {
        console.log(res);
        this.$modal.msgSuccess("保存成功");
        this.editData.label = this.$refs.rich.title;
        // this.currentDataObj=res.volume
        // this.currentType='1'
      });
    },
    saveBanbenDetail() {
      console.log(this.$refs.rich.editorContent);
      versionUpdate(
        this.editId,
        this.$refs.rich.title,
        this.$refs.rich.editorContent
      ).then((res) => {
        console.log(res);
        this.$modal.msgSuccess("保存成功");
        this.editData.label = this.$refs.rich.title;
        // this.currentDataObj=res.volume
        // this.currentType='1'
      });
    },
    saveZhangDetail() {
      chapterUpdate(
        this.editId,
        this.$refs.rich.title,
        this.$refs.rich.editorContent
      ).then((res) => {
        console.log(res);
        this.$modal.msgSuccess("保存成功");
        this.editData.label = this.$refs.rich.title;
      });
    },
    getJuanDetail(id) {
      this.editId = id;
      getVolumeDetail(id).then((res) => {
        console.log(res.volume);
        this.currentDataObj = res.volume;
        this.currentType = "1";
      });
    },
    getZhangDetail(chapterId) {
      getChapterContent(chapterId).then((res) => {
        console.log(res);
        this.currentDataObj = res;
        this.currentType = "2";
      });
    },
    getBanbenDetail(chapterId) {
      getVersionsContent(chapterId).then((res) => {
        console.log(res);
        this.currentDataObj = res;
        this.currentType = "3";
      });
    },
    handleTopClick(type) {
      if (type == "save") {
        if (this.currentType == 1) {
          this.saveJuanDetail();
        } else if (this.currentType == 2) {
          this.saveZhangDetail();
        } else {
          this.saveBanbenDetail();
        }
      } else if (type == "share") {
        console.log(this.editData, 22);
        if (this.editId) {
          if (this.editData.chap_id) {
            this.handleOpenShare2(this.editData);
          } else {
            this.handleOpenShare(this.editData);
          }
        }
      }
    },
    //故事框架 点击树节点 => 切换到对应章节(示例)
    handleTreeNodeClickBj(nodeData) {
      // nodeData: { id, label, ... }
      this.editId = nodeData.id;
      this.currentDataBj = nodeData;
      var that = this;
      setTimeout(function () {
        that.$refs.bjDetail.getItem();
      }, 500);
      // 这里可根据id请求后端获取标题和内容, 再设置currentDataObj

      // this.currentDataObj = { title:'xxx', content:'xxx' };
    },
    //章节版本 点击树节点 => 切换到对应章节(示例)
    handleTreeNodeClick(nodeData) {
      console.log(nodeData, 111);
      // nodeData: { id, label, ... }
      this.editId = nodeData.id;
      this.editData = nodeData;
      console.log(nodeData.level);
      if (nodeData.level == 1) {
        this.getJuanDetail(nodeData.id);
      } else if (nodeData.level == 2) {
        this.getZhangDetail(nodeData.id);
      } else {
        this.getBanbenDetail(nodeData.id);
      }

      // 这里可根据id请求后端获取标题和内容, 再设置currentDataObj
      // this.currentDataObj = { title:'xxx', content:'xxx' };
    },
    // 处理 node 的下拉菜单命令
    handleTreeNodeCommand({ command, nodeData }) {
      if (command === "rename") {
        // 例如重命名
        this.$prompt("请输入新名称", "重命名", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
        })
          .then(({ value }) => {
            nodeData.label = value;
          })
          .catch(() => {});
      } else if (command === "delete") {
        // 例如删除
        this.$confirm("确认删除该节点吗？", "提示", { type: "warning" })
          .then(() => {
            // 在treeData里把它移除
            this.removeNodeById(nodeData.id, this.treeData);
            this.$message.success("删除成功");
          })
          .catch(() => {});
      }
      // 其他 command 同理
    },
    handleTreeNodeCommandBj({ command, nodeData }) {
      if (command === "rename") {
        // 例如重命名
        this.$prompt("请输入新名称", "重命名", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
        })
          .then(({ value }) => {
            nodeData.label = value;
          })
          .catch(() => {});
      } else if (command === "delete") {
        // 例如删除
        this.$confirm("确认删除该节点吗？", "提示", { type: "warning" })
          .then(() => {
            // 在treeData里把它移除
            this.removeNodeById(nodeData.id, this.treeData);
            this.$message.success("删除成功");
          })
          .catch(() => {});
      }
      // 其他 command 同理
    },
    removeNodeById(id, arr) {
      for (let i = arr.length - 1; i >= 0; i--) {
        if (arr[i].id === id) {
          arr.splice(i, 1);
          return;
        } else if (arr[i].children) {
          this.removeNodeById(id, arr[i].children);
        }
      }
    },
    // AI生成稿题
    handleAiGenerateTitle() {
      this.$message.info("调用AI生成稿题逻辑(示例)");
    },
    // AI写作导航
    handleAiWritingGuide() {
      this.$message.info("打开AI写作导航弹窗(示例)");
    },
    // 保存
    handleSave() {
      this.$message.success("章节已保存(示例)");
      // 在真实场景，可将 currentDataObj.title 与 content 拆分，然后调用后端更新
    },
    // 发布
    handlePublish() {
      this.$message.success("章节已发布(示例)");
    },
    changeType(data) {
      console.log(data);
      this.activeP = data;
    },
    changeDldh(data) {
      // if (data.type == "close") {
      //   this.$refs.dldh.showLogo = false;
      // }
      // if (data.type == "show") {
      //   this.$refs.dldh.showLogo = true;
      // }
      if (data.type == "openNew") {
        // this.$refs.dldh.showLogo = true;
        this.$refs.dldh.getModels();
        this.$refs.dldh.openNew(data.id, data.show_prompt);
      }
      if (data.type == "openNew2") {
        // this.$refs.dldh.showLogo = true;
        this.$refs.dldh.openNew2(data.id, data.show_prompt);
      }
      console.log(data);
    },
    // 富文本编辑器内容变动
    onEditorContentChange(html) {
      // 这里拿到完整HTML(包含<h1>标题 + 正文)
      // 你可以解析出<h1>标签内容作为title, 剩余做content
      console.log("编辑器HTML变更 => ", html);
    },
  },
};
</script>

<style lang="scss" scoped>
.dialog-footer {
  .el-button {
    width: 119px;
  }

  .el-button + .el-button {
    margin-left: 32px;
  }
}

.create-page {
  display: flex;
  flex-direction: column;
  height: 100%;
  background: #f2f4f8;

  .main-body {
    display: flex;
    flex: 1;
    overflow: hidden; // 防止超出滚动

    .left-panel {
      background: #ffffff;
      border-radius: 0px 12px 0px 0px;
      padding: 5px 0;
      border-right: 1px solid #ebeef5;
      position: relative;
      overflow-y: auto;

      ::v-deep .el-tabs__nav-scroll {
        padding: 0 30px;
      }

      ::v-deep .el-tabs__nav-wrap::after {
        height: 1px;
      }

      ::v-deep .el-tabs__item {
        font-weight: bold;
      }

      ::v-deep .el-tabs__active-bar {
        height: 3px;
      }
    }

    .center-panel {
      flex: 1;
      display: flex;
      flex-direction: column;
      background: #fff;
      margin: 0 14px;
      border-radius: 12px 12px 0px 0px;

      ::v-deep .ql-toolbar.ql-snow {
        border-left: 0;
        border-right: 0;
        border-top: 0;
        border-bottom: 1px solid rgba(0, 0, 0, 0.08);
        padding: 10px 25px;
      }

      ::v-deep .ql-container.ql-snow {
        border: none;
        padding-top: 75px;
      }

      ::v-deep .ql-editor {
        padding: 16px 24px;
      }

      ::v-deep .ql-editor.ql-blank::before {
        font-size: 16px;
        color: rgba(0, 1, 27, 0.2);
        left: 24px;
        font-style: normal;
      }

      .editor-toolbar {
        margin-bottom: 16px;

        .el-button {
          margin-right: 8px;
        }
      }
    }

    .right-panel {
      width: 68px;
      border-radius: 12px 0px 0px 0px;
      background-color: #fff;
      position: relative;
      &.openLeft {
        z-index: 2;
      }
    }
  }
}

.tip {
  font-size: 18px;
  text-align: center;
  width: 320px;
  color: #00011b;
  line-height: 30px;
  margin: 0 auto;
}

.selectType {
  font-size: 12px;
  color: rgba(0, 1, 27, 0.5);
  text-align: center;
  line-height: 16px;
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 20px 0;

  i {
    width: 16px;
    height: 16px;
    border-radius: 50%;
    border: 1px solid rgba(0, 1, 27, 0.3);
    margin-right: 8px;
  }

  i.active {
    border: none;
    color: rgba(22, 93, 235, 1);
    font-size: 16px;
  }
}
</style>
